package com.haofengsoft.scce.common.security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by Administrator on 2014/12/17.
 */
public class DESUtil {
    private static String DESKey = "bf33b0bbc467fe47d39507efd95f02b22015-96"; // 字节数必须是8的倍数
    private static byte[] iv1 = {(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};
//    public static void main(String[] args) {
//        System.out.println("xyz");
//        DES des = new DES();
//        System.out.print(des.encrypt("abcdef"));
//byte[] srcBytes = decryptMode("12345678", "123456789012345678943210",
//        "c5e8faaf1a0e52ae".getBytes());

//    System.out.println("解密后的字符串:" + (new String(srcBytes)));


//    }

    public byte[] desEncrypt(byte[] plainText) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(iv1);
        DESKeySpec dks = new DESKeySpec(DESKey.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte data[] = plainText;
        byte encryptedData[] = cipher.doFinal(data);
        return encryptedData;
    }

    public String encrypt(String input) {
        String result = "input";
        try {
            result = base64Encode(desEncrypt(input.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public String base64Encode(byte[] s) {
        if (s == null)
            return null;
        return DESBase64.encodeToString(s, DESBase64.DEFAULT);

    }
    // keybyte为加密密钥，长度为24字节

    // src为加密后的缓冲区


}
